package rs.mbs2.epics.server.servlet;

import java.io.IOException;
import java.util.Date;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import rs.mbs2.epics.server.entity.User;
import rs.mbs2.epics.server.servlet.util.Validation;
import rs.mbs2.epics.server.session.dao.localinterface.UserDaoLocal;

@SuppressWarnings("serial")
public class LoginController extends HttpServlet {

	private static Logger log = Logger.getLogger(LoginController.class);
	
	@EJB
	private UserDaoLocal userDao;
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String emailAddress = request.getParameter("emailAddress");
		String password = request.getParameter("password");
		
		boolean isValid = true;
		
		isValid = Validation.validateString(emailAddress);
		isValid = Validation.validateString(password);
		
		if(!isValid) {
			log.info(new Date() + ": Uneti nevalidni podaci.");
			response.sendRedirect(response.encodeRedirectURL("./login.jsp"));
			return;
		}
		
		User user = userDao.findUserByEmailAndPassword(emailAddress, password);
		
		if(user == null) {
			response.sendRedirect(response.encodeRedirectURL("./login.jsp"));
			log.info(new Date() + ": Ne postoji korisnik.");
			return;
		} 
		
		log.info(new Date() + ": Ulogovan: " + user.getFirstname() + " " + user.getLastname() + "(ID: " + user.getId() + ")");
		request.getSession().setAttribute("user", user);
		
		//getServletContext().getRequestDispatcher("/home.jsp").forward(request, response);
		getServletContext().getRequestDispatcher("/HomeController").forward(request, response);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
	
}
